const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const userId = wxContext.OPENID;
  
  if (!userId) {
    return {
      code: 1,
      message: '用户未登录'
    };
  }
  
  try {
    const { studyRecordId, status, actualStartTime, actualEndTime, actualDuration, breakCount, focusScore, exitReason } = event;
    
    if (!studyRecordId || !status) {
      return {
        code: 2,
        message: '学习记录ID和状态不能为空'
      };
    }
    
    // 验证状态值
    const validStatuses = ['not_started', 'started', 'completed', 'cancelled'];
    if (!validStatuses.includes(status)) {
      return {
        code: 3,
        message: '无效的学习状态'
      };
    }
    
    // 验证学习记录是否属于当前用户
    console.log(`验证学习记录 ${studyRecordId} 是否属于用户 ${userId}`);
    
    try {
      const studyRecord = await db.collection('study_records').doc(studyRecordId).get();
      
      if (!studyRecord.data) {
        return {
          code: 404,
          message: '学习记录不存在'
        };
      }
      
      console.log(`找到学习记录: ${JSON.stringify(studyRecord.data)}`);
      
      if (studyRecord.data.userId !== userId) {
        console.log(`权限验证失败: 记录用户ID ${studyRecord.data.userId} 不匹配当前用户ID ${userId}`);
        return {
          code: 403,
          message: '无权限修改此学习记录'
        };
      }
    } catch (docError) {
      console.error(`查询学习记录失败，ID: ${studyRecordId}，错误:`, docError);
      
      // 尝试使用where查询
      console.log(`尝试使用where查询学习记录，ID: ${studyRecordId}`);
      const whereResult = await db.collection('study_records').where({
        _id: studyRecordId,
        userId: userId
      }).get();
      
      if (!whereResult.data || whereResult.data.length === 0) {
        return {
          code: 404,
          message: '学习记录不存在',
          error: docError.message
        };
      }
      
      console.log(`使用where查询找到学习记录: ${JSON.stringify(whereResult.data[0])}`);
    }
    
    // 构建更新数据
    const updateData = {
      status,
      updateTime: new Date()
    };
    
    // 根据状态添加相应字段
    if (actualStartTime !== undefined) updateData.actualStartTime = actualStartTime;
    if (actualEndTime !== undefined) updateData.actualEndTime = actualEndTime;
    if (actualDuration !== undefined) updateData.actualDuration = actualDuration;
    if (breakCount !== undefined) updateData.breakCount = breakCount;
    if (focusScore !== undefined) updateData.focusScore = focusScore;
    if (exitReason !== undefined) updateData.exitReason = exitReason;
    
    // 更新学习记录
    console.log(`更新学习记录 ${studyRecordId}，数据:`, updateData);
    
    try {
      await db.collection('study_records').doc(studyRecordId).update({
        data: updateData
      });
      console.log(`学习记录 ${studyRecordId} 更新成功`);
    } catch (updateError) {
      console.error(`更新学习记录失败，ID: ${studyRecordId}，错误:`, updateError);
      return {
        code: 500,
        message: '更新学习记录失败',
        error: updateError.message
      };
    }
    
    return {
      code: 0,
      message: '更新学习记录成功',
      data: {
        studyRecordId,
        status,
        updateTime: updateData.updateTime
      }
    };
  } catch (error) {
    console.error('更新学习记录出错:', error);
    return {
      code: 500,
      message: '服务器错误',
      error: error.message
    };
  }
};